﻿import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier

AF_data_frame=pd.read_excel("RR_seg_AF.xls",sheet_name="Sheet1",header=None)
nonAF_data_frame=pd.read_excel("RR_seg_nonAF.xls",sheet_name="Sheet1",header=None)


AF_data=AF_data_frame.to_numpy()
nonAF_data=nonAF_data_frame.to_numpy()



print(AF_data.shape,nonAF_data.shape)


plt.figure(figsize=(15,10),dpi=240)

x_index=np.linspace(1,30,30)
plt.plot(x_index,AF_data[0,:],'r',label='AF-1')
plt.plot(x_index,AF_data[1,:],'--r',label='AF-2')
plt.plot(x_index,nonAF_data[0,:],"b",label='nonAF-1')
plt.plot(x_index,nonAF_data[1,:],'--b',label='nonAF-2')

plt.legend(loc=1)
plt.ylim([125,325])
plt.show()

AF_input=np.empty([AF_data.shape[0],2])

AF_input[:,0]=np.mean(AF_data,axis=1)
AF_input[:,1]=np.std(AF_data,axis=1)
print(AF_input.shape)

nonAF_input=np.empty([nonAF_data.shape[0],2])

nonAF_input[:,0]=np.mean(nonAF_data,axis=1)
nonAF_input[:,1]=np.std(nonAF_data,axis=1)
print(nonAF_input.shape)


plt.figure(figsize=(15,10),dpi=240)
plt.plot(AF_input[:,0],AF_input[:,1],'.r',markersize=4)
plt.plot(nonAF_input[:,0],nonAF_input[:,1],'.b',markersize=4)
plt.xlim([50,350])
plt.xlabel('mean')
plt.ylim([0,100])
plt.ylabel("std")
plt.show()

AF_label=np.ones(AF_input.shape[0])
nonAF_label=np.zeros(nonAF_input.shape[0])
print(AF_label.shape,nonAF_label.shape)

#6.数据存储

#转化为pd的dataframe格式，方便存储。
AF_input_frame=pd.DataFrame(AF_input)
nonAF_input_frame=pd.DataFrame(nonAF_input)
AF_label_frame=pd.DataFrame(AF_label)
nonAF_label_frame=pd.DataFrame(nonAF_label)

#使用with上下文管理进行文件处理

with pd.ExcelWriter('pre_treatment_data.xlsx')as f:
    AF_input_frame.to_excel(f,sheet_name="AF_input",header=False,index=False)
    nonAF_input_frame.to_excel(f,sheet_name="nonAF_input",header=False,index=False)
    AF_label_frame.to_excel(f,sheet_name="AF_label",header=False,index=False)
    nonAF_label_frame.to_excel(f,sheet_name="nonAF_label",header=False,index=False)

#划分数据集
#80%作为训练集，20%作为测试集
AF_train_size=int(AF_data.shape[0]*0.8)
nonAF_train_size=int(nonAF_data.shape[0]*0.8)
x_train=np.concatenate([AF_input[0:AF_train_size,:],nonAF_input[0:nonAF_train_size,:]])
y_train=np.concatenate(([AF_label[0:AF_train_size],nonAF_label[0:nonAF_train_size]]))
x_test=np.concatenate([AF_input[AF_train_size:,:],nonAF_input[nonAF_train_size:,:]])
y_test=np.concatenate([AF_label[AF_train_size:],nonAF_label[nonAF_train_size:]])
print(x_train.shape,y_train.shape,x_test.shape,y_test.shape)

#训练模型
model=RandomForestClassifier(n_estimators=100,bootstrap=True,max_features='sqrt')
model.fit(x_train,y_train)

RandomForestClassifier(max_features='sqrt')

#进行预测
result=model.predict(x_test)
print(result.shape)
print(result)

#